How to get the sum for every distinct value in another column?
How to get the sum for every distinct value in another column?
20627-Jul-2023
Updated on 28-Jul-2023
Home / DeveloperSection / Forums / How to get the sum for every distinct value in another column?
How to get the sum for every distinct value in another column?
Aryan Kumar
28-Jul-2023Sure, you can get the sum for every distinct value in another column using the
GROUP BY
clause and theSUM()
function. The syntax is as follows:SQL
For example, if you have a table called
products
with the columnsname
andprice
, you could use the following SQL statement to get the sum of all product prices for each unique product name:SQL
This would return a table with two columns:
name
andsum
. Thename
column would contain the unique product names, and thesum
column would contain the sum of all product prices for each unique product name.Here is an example of how to get the sum for every distinct value in another column in MySQL:
SQL
This will return the following result:
As you can see, the
GROUP BY
clause has grouped the rows in theproducts
table by thename
column. TheSUM()
function has then been used to calculate the sum of all product prices for each unique product name.